<template>
  <!-- 交货单表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="80%"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="150"
      >
        <h4 class="mb-[20px] mt-[20px]">发货清单</h4>
        <el-card shadow="never" class="table-container">
          <template #header> </template>
          <div class="formTable">
            <el-table
              :data="formData.details"
              style="width: 100%"
              :key="Math.random"
              border
            >
              <el-table-column
                type="index"
                label="序号"
                align="center"
                width="100"
              />
              <el-table-column
                label="包装条码"
                props="topUnitId"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.topUnitId'"
                    :rules="rules.sontopUnitId"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.topUnitId"
                      placeholder="请输入列表显示的包装ID"
                      clearable
                    />
                    <span v-else>{{ row.topUnitId }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="物料号"
                props="materialNumber"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.materialNumber'"
                    :rules="rules.sonmaterialNumber"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.materialNumber"
                      placeholder="请输入物料号"
                      clearable
                    />
                    <span v-else>{{ row.materialNumber }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="物料名称"
                props="materialName"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.materialName'"
                    :rules="rules.sonmaterialName"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.materialName"
                      placeholder="请输入物料名称"
                      clearable
                    />
                    <span v-else>{{ row.materialName }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="生产批次"
                props="supplyBatch"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.supplyBatch'"
                    :rules="rules.sonsupplyBatch"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.supplyBatch"
                      placeholder="请输入生产批次"
                      clearable
                    />
                    <span v-else>{{ row.supplyBatch }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="物料数量"
                props="materialQuantity"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.materialQuantity'"
                    :rules="rules.sonmaterialQuantity"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.materialQuantity"
                      placeholder="请输入物料数量"
                      clearable
                    />
                    <span v-else>{{ row.materialQuantity }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="数量单位"
                props="unitCode"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.unitCode'"
                    :rules="rules.sonunitCode"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.unitCode"
                      placeholder="请输入数量单位"
                      clearable
                    />
                    <span v-else>{{ row.unitCode }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                align="center"
                label="操作"
                width="300"
                v-if="!props.isReadonly"
              >
                <template #default="scope">
                  <el-button
                    :disabled="formData.details.length < 2"
                    type="danger"
                    link
                    @click.stop="handleDelete(scope.$index)"
                    ><i-ep-delete />
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "SRMWMSDELIVERYADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  deliveryCode: "",
  materialDocumentId: "",
  materialDocumentCode: "",
  deliveryType: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  saleOrderId: "",
  extenalSaleOrderCode: "",
  saleOrderCode: "",
  customerId: "",
  customerCode: "",
  customerName: "",
  dstCustomerId: "",
  dstCustomerCode: "",
  dstCustomerName: "",
  outboundAddressId: "",
  outboundAddressDesc: "",
  outboundContact: "",
  outboundPhone: "",
  inboundAddressId: "",
  inboundAddressDesc: "",
  inboundContact: "",
  inboundPhone: "",
  outboundPlantId: "",
  outboundPlantCode: "",
  outboundPlantName: "",
  outboundStorageLocationId: "",
  outboundStorageLocationCode: "",
  outboundStorageLocationName: "",
  purchaseOrderId: "",
  purchaseOrderCode: "",
  extenalPurchaseOrderCode: "",
  supplierId: "",
  supplierCode: "",
  supplierName: "",
  inboundPlantId: "",
  inboundPlantCode: "",
  inboundPlantName: "",
  inboundStorageLocationId: "",
  inboundStorageLocationCode: "",
  inboundStorageLocationName: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  deleted: "",
  outboundStorageSectionId: "",
  outboundStorageSectionCode: "",
  isExecuted: "",
  details: [
    {
      id: "",
      organizationId: "",
      organizationCode: "",
      organizationName: "",
      plantId: "",
      plantCode: "",
      plantName: "",
      partnerId: "",
      partnerCode: "",
      parentUnitId: "",
      topUnitId: "",
      deliveryId: "",
      materialId: "",
      materialNumber: "",
      materialName: "",
      supplyBatch: "",
      arriveDate: "",
      orderScheduleId: "",
      supplyMaterialType: "",
      unitBarcode: "",
      materialQuantity: "",
      unitCode: "",
      ownAssets: "",
      unitLevel: "",
      unitShowFlag: "",
      version: "",
      remarks: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      deleted: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  inboundPlantId: [
    { required: true, message: "请输入到货工厂id;内向交货", trigger: "blur" },
  ],
  inboundPlantCode: [
    { required: true, message: "请输入到货工厂编号", trigger: "blur" },
  ],
  inboundPlantName: [
    { required: true, message: "请输入到货工厂名称", trigger: "blur" },
  ],
  inboundStorageLocationId: [
    { required: true, message: "请输入到货地点id;内向交货", trigger: "blur" },
  ],
  inboundStorageLocationCode: [
    { required: true, message: "请输入到货地点编号", trigger: "blur" },
  ],
  inboundStorageLocationName: [
    { required: true, message: "请输入到货地点名称", trigger: "blur" },
  ],
  createTime: [{ required: true, message: "请输入创建时间", trigger: "blur" }],
  createdUserId: [{ required: true, message: "请输入创建人", trigger: "blur" }],
  sontopUnitId: [
    { required: true, message: "请输入列表显示的包装ID", trigger: "blur" },
  ],
  sonmaterialNumber: [
    { required: true, message: "请输入物料号", trigger: "blur" },
  ],
  sonmaterialName: [
    { required: true, message: "请输入物料名称", trigger: "blur" },
  ],
  sonsupplyBatch: [
    { required: true, message: "请输入生产批次", trigger: "blur" },
  ],
  sonmaterialQuantity: [
    { required: true, message: "请输入物料数量", trigger: "blur" },
  ],
  sonunitCode: [{ required: true, message: "请输入数量单位", trigger: "blur" }],
});

/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
};

const details = {
  id: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  plantId: "",
  plantCode: "",
  plantName: "",
  partnerId: "",
  partnerCode: "",
  parentUnitId: "",
  topUnitId: "",
  deliveryId: "",
  materialId: "",
  materialNumber: "",
  materialName: "",
  supplyBatch: "",
  arriveDate: "",
  orderScheduleId: "",
  supplyMaterialType: "",
  unitBarcode: "",
  materialQuantity: "",
  unitCode: "",
  ownAssets: "",
  unitLevel: "",
  unitShowFlag: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [details];
  formData.id = "";
  formData.deliveryCode = "";
  formData.materialDocumentId = "";
  formData.materialDocumentCode = "";
  formData.deliveryType = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.organizationName = "";
  formData.saleOrderId = "";
  formData.extenalSaleOrderCode = "";
  formData.saleOrderCode = "";
  formData.customerId = "";
  formData.customerCode = "";
  formData.customerName = "";
  formData.dstCustomerId = "";
  formData.dstCustomerCode = "";
  formData.dstCustomerName = "";
  formData.outboundAddressId = "";
  formData.outboundAddressDesc = "";
  formData.outboundContact = "";
  formData.outboundPhone = "";
  formData.inboundAddressId = "";
  formData.inboundAddressDesc = "";
  formData.inboundContact = "";
  formData.inboundPhone = "";
  formData.outboundPlantId = "";
  formData.outboundPlantCode = "";
  formData.outboundPlantName = "";
  formData.outboundStorageLocationId = "";
  formData.outboundStorageLocationCode = "";
  formData.outboundStorageLocationName = "";
  formData.purchaseOrderId = "";
  formData.purchaseOrderCode = "";
  formData.extenalPurchaseOrderCode = "";
  formData.supplierId = "";
  formData.supplierCode = "";
  formData.supplierName = "";
  formData.inboundPlantId = "";
  formData.inboundPlantCode = "";
  formData.inboundPlantName = "";
  formData.inboundStorageLocationId = "";
  formData.inboundStorageLocationCode = "";
  formData.inboundStorageLocationName = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.deleted = "";
  formData.outboundStorageSectionId = "";
  formData.outboundStorageSectionCode = "";
  formData.isExecuted = "";
}

const loading = ref(false);

/** 交货单保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/srm/wmsdelivery/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/srm/core/wmsdelivery/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}
:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
  height: 65vh;
}
:deep.el-input.el-input--default.el-input--suffix {
  // 固定宽度
  width: 190px !important;
}
</style>
